package com.jic.market.impl;

import com.google.common.collect.Lists;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.market.common.constant.PatchGrouponInstConstant;
import com.jic.market.common.constant.PatchGrouponInstDetailConstant;
import com.jic.market.common.enums.DeleteFlagEnum;
import com.jic.market.entity.*;
import com.jic.market.mapper.PatchGrouponDetailEntityMapper;
import com.jic.market.mapper.PatchGrouponInstEntityMapper;
import com.jic.market.mapper.PatchGrouponMpEntityMapper;
import com.jic.market.orm.Pagination;
import com.jic.market.request.PatchGrouponInstRequest;
import com.jic.market.request.manager.patchgroup.PatchGrouponInstForceGroupRequest;
import com.jic.market.response.PageResponse;
import com.jic.market.response.PatchGrouponInstResponse;
import com.jic.market.response.PatchGrouponThemeResponse;
import com.jic.market.response.manager.patchgroup.PatchGrouponInstForceGroupResponse;
import com.jic.market.service.PPatchGrouponCustomerRobotService;
import com.jic.market.service.PatchGrouponInstService;
import com.jic.common.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author guohuayong
 * @date: 2020年01月20日
 */
@Service
public class PatchGrouponInstServiceImpl implements PatchGrouponInstService {
    @Autowired
    PatchGrouponInstEntityMapper curMapper;

    @Resource
    PPatchGrouponCustomerRobotService pPatchGrouponCustomerRobotService;

    @Resource
    PatchGrouponDetailEntityMapper detailEntityMapper;

    @Autowired
    private PatchGrouponMpEntityMapper patchGrouponMpEntityMapper;

    @Override
    public PageResponse<PatchGrouponInstResponse> query(PatchGrouponInstRequest request) {
        Pagination pagination = Pagination.build(request.getStart(), request.getLimit(), request.genOrderBys());
        if(request.getEndLaunchTime() != null){
            request.setEndLaunchTime(DateUtils.getEndOfDay(request.getEndLaunchTime()));
        }
        List<PatchGrouponInstResponse> list = curMapper.list(request, pagination);
        int count = curMapper.listCount(request);

        list = Optional.ofNullable(list).orElse(Lists.newArrayList()).stream().map(e->{
            e.setStatusName(PatchGrouponInstConstant.StatusEnum.getRemarkByCode(e.getStatus()));
            return e;
        }).collect(Collectors.toList());


        PageResponse<PatchGrouponInstResponse> responsePageResponse = new PageResponse<PatchGrouponInstResponse>()
                .setPageNo(request.getPageNo())
                .setPageSize(request.getPageSize())
                .setTotal(count)
                .setRows(list);

        return responsePageResponse;
    }

    @Override
    public PatchGrouponInstResponse detail(PatchGrouponInstRequest t) {
        PatchGrouponInstResponse response = curMapper.detail(t);
        if (null != response) {
            response.setStatusName(PatchGrouponInstConstant.StatusEnum.getRemarkByCode(response.getStatus()));
            response.setDetailResponseList(Optional.ofNullable(response.getDetailResponseList()).orElse(Lists.newArrayList()).stream().map(e -> {
                e.setStatusName(PatchGrouponInstDetailConstant.StatusEnum.getRemarkByCode(e.getStatus()));
                e.setPaymentStatusName(PatchGrouponInstDetailConstant.PaymentStatusEnum.getRemarkByCode(e.getPaymentStatus()));
                return e;
            }).collect(Collectors.toList()));
        }

        // TODO 根据实例id 查询实例
        PatchGrouponInstEntity instCondition =new PatchGrouponInstEntity();
        instCondition.setId(t.getId());
        instCondition.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        PatchGrouponInstEntity instEntity = curMapper.query(instCondition);

        // TODO 根据实例中的ref_patch_groupon_theme，和 mpId(需要增加), 查询patch_groupon_mp的pic_url
        Long promtionId = instEntity.getRefPatchGrouponTheme();
//        Long mpId = null;
        Long mpId = instEntity.getMpId();

        PatchGrouponMpEntity grouponMpCondition =new PatchGrouponMpEntity();
        grouponMpCondition.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        grouponMpCondition.setPromotionId(promtionId);
        grouponMpCondition.setMpId(mpId);
        PatchGrouponMpEntity mpEntity = patchGrouponMpEntityMapper.query(grouponMpCondition);
        String picUrl =mpEntity.getPicUrl();
        response.setPicUrl(picUrl);
        return response;
    }

    @Override
    public PatchGrouponInstForceGroupResponse forceGroup(PatchGrouponInstForceGroupRequest request) {

        PatchGrouponInstForceGroupResponse response =new PatchGrouponInstForceGroupResponse();
        // TODO 根据实例id 查看这是几人团  m
        PatchGrouponInstEntity queryInstCondition =new PatchGrouponInstEntity();
        queryInstCondition.setId(request.getPatchGrouponInstId());
        PatchGrouponInstEntity instEntity = curMapper.query(queryInstCondition);

        Integer totalMembers = instEntity.getTotalMembers();

        // TODO 根据实例id  查看 patch_groupon_detail 查询当前已经拼团的数量n
        Integer joinedMembers = instEntity.getJoinedMembers();

        // TODO 从patch_groupon_customer_robot  获取 m-n 个机器人
        Integer left = totalMembers -joinedMembers;

        PatchGrouponCustomerRobotModel robotCondition =new PatchGrouponCustomerRobotModel();
        robotCondition.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());

        Random r = new Random();
        int ran1 =r.nextInt(5)+1;

        Page pageQuery =new Page();
        pageQuery.setStart(ran1);
        pageQuery.setLimit(left);

        PageResult<PatchGrouponCustomerRobotModel> robots = pPatchGrouponCustomerRobotService.patchGrouponCustomerRobotQueryPageList(robotCondition, pageQuery);

        // TODO 插入机器人 patch_groupon_detail
        List<PatchGrouponDetailEntity> list =new ArrayList<>();
        List<PatchGrouponCustomerRobotModel> robotList = robots.getRows();

        robotList.forEach(x ->{
            PatchGrouponDetailEntity detailEntity =new PatchGrouponDetailEntity();
            detailEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            detailEntity.setCellPhone(x.getCellPhone());
            detailEntity.setCustomerId(x.getCustomerId());
            detailEntity.setPaymentType(1);
            detailEntity.setStatus(3);
            detailEntity.setReceiveAddress(x.getReceiveAddress());
            detailEntity.setReceiveMember(x.getReceiveMember());
            detailEntity.setRefPatchGrouponInst(instEntity.getId());
            detailEntity.setSourceRef(0L);
            detailEntity.setRefPatchGrouponTheme(instEntity.getRefPatchGrouponTheme());
            detailEntity.setJoinTime(new Date());
            detailEntity.setOrderCode("----");
            detailEntityMapper.insert(detailEntity);
        });

        // TODO 更新 patch_groupon_inst 中 joined_members ，completed_time ,status ,update_time

        PatchGrouponInstEntity instEntityUpdate =new PatchGrouponInstEntity();
        instEntityUpdate.setId(instEntity.getId());
        instEntityUpdate.setJoinedMembers(instEntity.getTotalMembers());
        instEntityUpdate.setCompletedTime(new Date());
        instEntityUpdate.setStatus(3);
        instEntityUpdate.setUpdateTime(new Date());

        int count = curMapper.update(instEntityUpdate);
        response.setCount(count);
        return response;
    }

    @Override
    public Integer addInstEntity(PatchGrouponInstEntity instEntity) {
        int count = curMapper.insert(instEntity);
        return count;
    }

    @Override
    public PatchGrouponInstEntity queryEntity(PatchGrouponInstEntity instEntity) {
        PatchGrouponInstEntity initEntity = curMapper.query(instEntity);
        return initEntity;
    }

    @Override
    public Integer update(PatchGrouponInstEntity instEntity) {
        instEntity.setUpdateTime(new Date());
        int count = curMapper.update(instEntity);
        return count;
    }

    @Override
    public List<PatchGrouponInstEntity> findOfPage(PatchGrouponInstEntity instEntity, Pagination page) {
        List<PatchGrouponInstEntity> instEntityList = curMapper.findOfPage(instEntity, page);
        return instEntityList;
    }


    @Override
    public Integer countOfPage(PatchGrouponInstEntity instEntity) {
        int count = curMapper.countOfPage(instEntity);
        return count;
    }

}
